package com.whz.enummap.transitionenummap;

import java.util.EnumMap;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;

/**
 * @Author: sinosoft
 * @Description:
 * 每个阶段过渡都是通过一对阶段枚举进行索引的
 * 将这种关系表示为一个映射
 * 映射的键是一个枚举(起始阶段), 值为另一个映射,这第二个映射的键为第二个枚举(目标阶段),它的值为结果(阶段过渡)
 * 形成了Map(起始阶段, Map(目标阶段,阶段过渡))
 * @Date: Create in 10:56 2021/5/17
 * @Modified By:
 */
public enum Phase {
    SOLID, LIQUID, GAS;
    public enum Transition {
        MELT(SOLID, LIQUID),
        FREEZE(LIQUID, SOLID),
        BOIL(LIQUID, GAS),
        CONDENSE(GAS, LIQUID),
        SUBLIME(SOLID, GAS),
        DEPOSIT(GAS, SOLID);
        private final Phase from;
        private final Phase to;

        Transition(Phase from, Phase to) {
            this.from = from;
            this.to = to;
        }
        private static final Map<Phase, Map<Phase, Transition>> m =
                Stream.of(values()).
                        collect(groupingBy(t -> t.from,
                                () -> new EnumMap<>(Phase.class),
                                toMap(t -> t.to,
                                        t -> t,
                                        (x, y) -> y,
                                        () -> new EnumMap<>(Phase.class))));
        public static Transition from(Phase from, Phase to) {
            return m.get(from).get(to);
        }
    }
}
